Page({

  data:{
    buttonStyle:"",
    checked:false,
    loginStyle:"",
    codeDisabled:true,
    loginDisabled:true,
    tel:"",
    code:""
  },
  // 获取用户输入的手机号
  getTel(event){
    let tel = event.detail.value
    this.setData({
      tel:tel
    })
  },
  //获取用户输入的验证码
  getCode(event){
    let code = event.detail.value
    this.setData({
      code:code
    })
  },
  //验证手机号
  isTel(event){
    let tel = event.detail.value
    //通过正则表达式判断输入的手机号是否正确
    const res = /^[1][3,4,5,6.7,8,9][0-9]{9}$/
    if(!res.test(tel)){
      wx.showToast({
        title: '手机号错误',
        icon:'error',
        duration: 3000
      })
      this.setData({
        buttonStyle:"",
        codeDisabled: true
      })
    }else{
      // 将发送验证码按钮的样式变成红色
      this.setData({
        buttonStyle:"btn",
        codeDisabled: false
      })
    }



  },
  // 更改radio的选中状态
  checkedTap(){
    let tel = this.data.tel
    let code = this.data.code
    this.setData({
      checked:!this.data.checked
    })
    if(this.data.checked && tel != "" && code != ""){
      this.setData({
        loginStyle:"loginbtn",
        loginDisabled:false
      })
    }else{
      this.setData({
        loginStyle:"",
        oginDisabled:true
      })
    }
  },
  //发送验证码
  sendCode(){
    //携带手机号前往服务器 去给改手机号发送短信
    let tel = this.data.tel
    wx.request({
      url: 'http://localhost:9527/users/code/'+tel,
      method:'GET',
      success: res =>{
        if(res.data.code == 0){
          wx.showToast({
            title: '发送成功',
          })
        }else{
          wx.showToast({
            title: '系统异常',
            icon:"error"
          })
        }
      }
    })
  },
  //登陆
  login(){
    wx.request({
      url: 'http://localhost:9527/users/login',
      method: "POST",
      data:{
        telephone:this.data.tel,
        code:this.data.code
      },
      success: res => {
        console.log(res)
        if(res.data.code == 0){
          // 先将用户登录信息进行存储
          wx.setStorageSync('userInfo', res.data.data)
          wx.navigateBack()
        }
      }
    })
  }
})